package com.njcb.ams.bootconfig;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.scheduler.bean.AutowiringSpringBeanJobFactory;

@Configuration
@Component
@EnableScheduling
public class SpringQuartzConfig {
	
	@Autowired
	public PlatformTransactionManager transactionManager;
	@Autowired
	public DataSource dataSource;
	
	
	@Bean
	public JobFactory jobFactory(ApplicationContext applicationContext) throws IOException {
		AutowiringSpringBeanJobFactory jobFactory = new com.njcb.ams.scheduler.bean.AutowiringSpringBeanJobFactory();
		jobFactory.setApplicationContext(applicationContext);
		return jobFactory;
	}
	
	
	@Bean(name="schedulerFactoryBean")
	public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws IOException {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		factory.setQuartzProperties(quartzProperties());
		factory.setDataSource(dataSource);
		factory.setTransactionManager(transactionManager);
		factory.setSchedulerName("AmsScheduler");
		factory.setOverwriteExistingJobs(true);
		//<!-- 不自动启动，系统初始化时启动-->
		factory.setAutoStartup(false);
		factory.setStartupDelay(30);
		factory.setApplicationContext(AppContext.getContext());
		factory.setJobFactory(jobFactory);
		return factory;
	}

	@Bean
	public Properties quartzProperties() throws IOException {
		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
		propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
		//读取quartz.properties后再初始化对象
		propertiesFactoryBean.afterPropertiesSet();
		return propertiesFactoryBean.getObject();
	}
	
}
